import CRS from "./CRS";
import { toTransformation } from "../geometry/Transformation";

import ProjectEPSG4326 from "../geo/Projection.EPSG4326";
import { toPoint } from "../geometry/Point";

export default class CRSEPSG4326 extends CRS {
  code = "EPSG:4326";
  projection = new ProjectEPSG4326();
  transformation;
  constructor() {
    super();
    this.setTransformation();
  }
  setTransformation() {
    // const scale = 0.5 / (Math.PI * this.projection.R);
    // this.transformation = toTransformation(scale, 0.5, -scale, 0.5);
    this.transformation = toTransformation(1 / 180, 1, -1 / 180, 0.5);
  }
  // 经纬度转点
  lngLatToPoint(lnglat, zoom) {
    // 把经纬度转web墨卡托投影
    const projectedPoint = this.projection.project(lnglat),
      scale = this.scale(zoom);
    // 墨卡托投影的原点在非洲旁边，把他偏移到瓦片原点
    return this.transformation._transform(projectedPoint, scale);
  }

  // 点转经纬度
  pointToLatLng(point, zoom) {
    const scale = this.scale(zoom),
      untransformedPoint = this.transformation.untransform(point, scale);

    return this.projection.unproject(untransformedPoint);
  }
  bbox(x, y, z) {
    const point = toPoint(x, y);
    const size = toPoint(256, 256);

    const startPoint = point.scaleBy(size);
    const endPoint = startPoint.add(size);
    const leftTop = this.pointToLatLng(startPoint, z)
    const  rightBottom= this.pointToLatLng(endPoint, z)
    return [
      leftTop.lng,
      rightBottom.lat,
      rightBottom.lng,
      leftTop.lat,
    ].toString();
  }
}

export const EPSG4326 = () => {
  return new CRSEPSG4326();
};
